//
//  BankCardBindingViewController.m
//  NiuBanJin
//
//  Created by Billy on 15/10/19.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "BankCardBindingViewController.h"
#import "DepositSuccessViewController.h"
#import "BankSelectionViewController.h"
#import "BCTextFieldForPlaceHolder.h"
#import "DepositSuccessViewController.h"

@interface BankCardBindingViewController ()<LLPaySdkDelegate,UITextFieldDelegate>

@property (nonatomic, strong) NSMutableDictionary *mutableDic_text;
@property (nonatomic, strong) UIView *view_content; // parent view
@property (nonatomic, strong) UIView *view_header;
@property (nonatomic, strong) UILabel *label_promtRate ;//收益率显示，根据输入金额变而变
@property (nonatomic, strong) UIScrollView *view_scroll ;//支持4S/5
@property (nonatomic, strong) UILabel *label_bank;

@property (nonatomic, strong) LLPaySdk *sdk; //连连支付SDK
@property (nonatomic, copy) NSString *str_order_no;
@property (nonatomic, assign) CGFloat user_currentRate; //用户当前利率

@end

@implementation BankCardBindingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self pageSettingsAndSubviewsCreation];
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.view setBackgroundColor:BASECOLOR];
    
    [self.navigationItem setTitle:@"绑定存入"];
    [self.view addSubview:self.view_content];
    
    
    //取出 当前的利率
    
    User *tmp = [[UserManager sharedUserManager] getCurrentUser];
    self.user_currentRate =  tmp.user_annualRate.floatValue + tmp.user_ticketRate.floatValue ;
}

#pragma mark - setter methods

- (UIView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [[UIView alloc] initWithFrame:CGRectMake(0, MULTIPLYHEIGHT(40.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT((460.0)/2))];
        [_view_header setBackgroundColor:[UIColor whiteColor]];

        // 添加label/textfield
        for (int i = 0; i < 2; i ++) {
            
            UILabel *label_title = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(36.0/2) + i *MULTIPLYHEIGHT(100.0/2), MULTIPLYWIDTH(200.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#434343"] fontName:[UIFont systemFontOfSize:15.0] text:self.mutableDic_text[@"title"][i]];
            
            [_view_header addSubview:label_title];
            
            BCTextField *textFiled_tmp = [[BCTextField alloc] initWithFrame:CGRectMake(MULTIPLYWIDTH(20.0/2) + CGRectGetMaxX(label_title.frame), i * MULTIPLYHEIGHT(99.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(20.0/2)- CGRectGetMaxX(label_title.frame)  , MULTIPLYHEIGHT(99.0/2))];
            [textFiled_tmp setTag:(i  +50)];
            [textFiled_tmp setDelegate:self];//放代理的目的是为了防止用户输入99. , 而不是99
            
            if (i == 0) {
                
                if ([UsefulUtil isChinese:GETCURRENTUSERINOBYPRAMETERES(user_userRealName)]) { //有姓名代入进来
                    
                    [textFiled_tmp setText:GETCURRENTUSERINOBYPRAMETERES(user_userRealName)];
                    [textFiled_tmp setEnabled:NO];
                }
                
            }else {
                
                [textFiled_tmp setKeyboardType:UIKeyboardTypeDecimalPad];
                [textFiled_tmp setRegx:@"^[0-9]{0,6}+(\\.[0-9]{0,2})?$"];
                [textFiled_tmp addTarget:self action:@selector(rateCalculation:) forControlEvents:UIControlEventEditingChanged];
            }
                
            [textFiled_tmp setPlaceholder:self.mutableDic_text[@"placeHolder"][i] ];
            
            [_view_header addSubview:textFiled_tmp];
            
            UIView *view_sep = [UsefulUtil viewCreationWithFrame:CGRectMake(0, (i +1) * MULTIPLYHEIGHT(99.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(1.0/2)) backgroundColor:[UsefulUtil colorWithHexString:@"#c7c7cd"] backGroundImage:nil];
            
            [_view_header addSubview:view_sep];
        }
        
        UILabel *label_promt = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(200.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(60.0/2)) textColor:[UsefulUtil colorWithHexString:@"#b3b3b3"] fontName:[UIFont systemFontOfSize:11.0] text:@""];
        self.label_promtRate = label_promt ;
        
        [label_promt setBackgroundColor:BASECOLOR];        
        [_view_header addSubview:label_promt];
        
        UIView *view_padding = [[UIView alloc] initWithFrame:CGRectMake(0, label_promt.frame.origin.y, MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(60.0/2))];
        [view_padding setBackgroundColor:BASECOLOR];
        [_view_header addSubview:view_padding];
        
        // 下面三个textFiled
        
        for (int i = 0; i < 2; i ++) {
            
            UILabel *label_title = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2),  MULTIPLYHEIGHT(296.0/2)+i *MULTIPLYHEIGHT(100.0/2), MULTIPLYWIDTH(200.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#434343"] fontName:[UIFont systemFontOfSize:15.0] text:self.mutableDic_text[@"title"][i+2]];
            
            [_view_header addSubview:label_title];
            
            // 加上选择银行按钮
            
            BCTextField *textFiled_tmp = [[BCTextField alloc] initWithFrame:CGRectMake(MULTIPLYWIDTH(20.0/2) + CGRectGetMaxX(label_title.frame), i * MULTIPLYHEIGHT(99.0/2) + MULTIPLYHEIGHT(260.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(20.0/2)- CGRectGetMaxX(label_title.frame)  , MULTIPLYHEIGHT(99.0/2))];
            
            [textFiled_tmp setTag:(i  +52)];
            
            if (i == 1) {
                
                [textFiled_tmp setKeyboardType:UIKeyboardTypeNumberPad];
                [textFiled_tmp setRegx:@"^[0-9]{0,19}$"];
            }
            [textFiled_tmp setPlaceholder:self.mutableDic_text[@"placeHolder"][i+2] ];
            [_view_header addSubview:textFiled_tmp];
            
            // 选择银行的时候textfiled 不能编辑
            if (i == 1) {
                
                [textFiled_tmp setKeyboardType:UIKeyboardTypeNumberPad];
            }else if (i == 0) {
                
                UILabel *label_tmp = [UsefulUtil labelCreationWithFrame:textFiled_tmp.frame textColor:[UsefulUtil colorWithHexString:@"#c7c7cd"] fontName:[UIFont systemFontOfSize:15.0] text:@"请选择银行"];
                self.label_bank = label_tmp;
                
                [label_tmp setUserInteractionEnabled:YES];
                [textFiled_tmp removeFromSuperview];
                [_view_header addSubview:label_tmp];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bankSelection:)];
                
                [label_tmp addGestureRecognizer:tap];
        
                // 右边箭头
                UIImageView *imagview_tmp = [UsefulUtil imageViewCreationWithFrame:CGRectMake(label_tmp.bounds.size.width - MULTIPLYWIDTH(54.0/2), MULTIPLYHEIGHT(30.0/2), MULTIPLYWIDTH(24.0/2), MULTIPLYHEIGHT(41.0/2)) image:[UIImage imageNamed:@"arrow"]];
                
                [label_tmp addSubview:imagview_tmp];
            }
            
            UIView *view_sep = [UsefulUtil viewCreationWithFrame:CGRectMake(0, MULTIPLYHEIGHT(260.0/2) +i  * MULTIPLYHEIGHT(99.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(1.0/2)) backgroundColor:[UsefulUtil colorWithHexString:@"#c7c7cd"] backGroundImage:nil];
            
            [_view_header addSubview:view_sep];
        }
    }
    
    return _view_header;
}

- (UIView *)view_content {
    
    if (!_view_content) {
        
        _view_content = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT((40.0 + 400.0+60.0+50.0+62.0+90.0+44.0+120.0)/2))];

        UIView *view_top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(40.0/2))];
        [view_top setBackgroundColor:BASECOLOR];
    
        [_view_content addSubview:view_top];
    
        [_view_content addSubview:self.view_header];
        
        //给里面的textfiled设定值
        
        [self setKeyBoardAndCorrespondingLimitationForTextFiledInViewHeader];
        
        //提示奖励
        
        NSString *str_promt = @"存入成功可获得黄色加息券一张和1000积分";
        UILabel *label_prompt = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(self.view_header.frame) + MULTIPLYHEIGHT(20.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(30.0/2)) textColor:[UsefulUtil colorWithHexString:@"#b3b3b3"] fontName:[UIFont systemFontOfSize:11.0] text:str_promt];
        
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str_promt];
        
        [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(7, 5)];
        [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(15, 5)];
        
        [label_prompt setAttributedText:attrStr];
        
        [_view_content addSubview:label_prompt];
        
        //button
        
        UIButton *button_authentication = [UsefulUtil buttonCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(label_prompt.frame) + MULTIPLYHEIGHT(40.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(90.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont systemFontOfSize:14.0] text:@"下一步"];
        
        [button_authentication addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [button_authentication setTag:10];
        [button_authentication setBackgroundColor:REDCOLOR];
        
        [_view_content addSubview:button_authentication];
        
        // 温馨提示
        
        UIImageView *imageView = [UsefulUtil imageViewCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(button_authentication.frame) + MULTIPLYHEIGHT(28.0/2), MULTIPLYWIDTH(23.0/2), MULTIPLYWIDTH(20.0/2)) image:[UIImage imageNamed:@"heart"]];
        
        [_view_content addSubview:imageView];
        
        
        UILabel *label_promptMiddle = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), imageView.frame.origin.y - MULTIPLYHEIGHT(4.0/2), MULTIPLYWIDTH(100.0/2), MULTIPLYHEIGHT(30.0/2))];
        
        [label_promptMiddle setTextColor:[UsefulUtil colorWithHexString:@"#989898"]];
        [label_promptMiddle setText:@"温馨提示"];
        [label_promptMiddle setFont:[UIFont systemFontOfSize:11.0]];
        [_view_content addSubview:label_promptMiddle];
        
        //最下面的
        UILabel *label_promptBottom = [UsefulUtil labelCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), CGRectGetMaxY(label_promptMiddle.frame) + MULTIPLYHEIGHT(16.0/2), SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(60.0/2)) textColor:[UsefulUtil colorWithHexString:@"#989898"] fontName:[UIFont systemFontOfSize:11.0] text:@"银行卡只可以使用实名认证同名借记卡移动端存入有限额，具体金额以银行为准。为了更多人享受牛钱包带来的便利，每人上限总额十万元。"];
        [label_promptBottom setNumberOfLines:0];
        [_view_content addSubview:label_promptBottom];
    
     }
    
    return _view_content;
}

- (NSMutableDictionary *)mutableDic_text {
    
    if (!_mutableDic_text) {
        
        _mutableDic_text = [NSMutableDictionary dictionary];
        
        [_mutableDic_text setObject:@[@"持卡人姓名",@"存入金额 (元)",@"选择银行",@"银行卡卡号"] forKey:@"title"];
        [_mutableDic_text setObject:@[@"请输入姓名",@"请输入存入金额≥100元",@"请选择所属银行",@"请输入银行卡卡号"] forKey:@"placeHolder"];
    }
    
    return _mutableDic_text;
}

- (LLPaySdk *)sdk{

    if (!_sdk) {
        
        _sdk = [[LLPaySdk alloc] init];
        [_sdk setSdkDelegate:self];
    }
    
    return _sdk;
}

#pragma mark - textFiled delegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField.tag == 51) { //金额框
        
        if ([textField.text componentsSeparatedByString:@"."].count == 1) { //处理009 ,09
            
            float value = textField.text.floatValue;
            textField.text = [NSString stringWithFormat:@"%.f",value];
            
        }else if ([textField.text componentsSeparatedByString:@"."].count == 2) { //处理09.，09.0，0.91
            
            if ([[[textField.text componentsSeparatedByString:@"."] lastObject] isEqualToString:@"0"]) {
                
                float value = textField.text.floatValue;
                textField.text = [NSString stringWithFormat:@"%.f",value];
            }else if([[textField.text  substringWithRange:NSMakeRange(textField.text.length -1 , 1)] isEqualToString:@"."]){ //处理 90. 这样的情况
                
                float value = textField.text.floatValue;
                textField.text = [NSString stringWithFormat:@"%.f",value];
            }
        }
    }
}

#pragma mark - button events handing

- (void) buttonClicked: (UIButton *) button {
    
    NSLog(@"need to call server interface to make sure success saving");

    switch (button.tag) {
        case 10:
        {
            [self accessServerToGetSignParamsBeforeJumpToLianLian];
 
        }
            break;
            
        default:
            break;
    }
}

- (void) accessServerToGetSignParamsBeforeJumpToLianLian { //访问server得到签名参数
    
    // 记得加上空值的判定
    
    BCTextField *textField_name = (BCTextField *)[self.view_header viewWithTag:50];
    UITextField *textField_amount = (UITextField *)[self.view_header viewWithTag:51];
    UITextField *textField_cardNo = (UITextField *)[self.view_header viewWithTag:53];
    
    if (![UsefulUtil isChinese:textField_name.text] || [textField_name.text isEqualToString:@""]) {
        
        [UsefulUtil showAlertView:@"请输入正确的中文姓名!"];
        
        return;
    }else if([textField_amount.text isEqualToString:@""]) {
        
        [UsefulUtil showAlertView:@"交易金额不能为空!"];
        return;
    }else if([textField_amount.text floatValue] < 0.001) {
        
        [UsefulUtil showAlertView:@"交易金额不能小于100元!"];
        return;
    }else if([textField_cardNo.text isEqualToString:@""] || (textField_cardNo.text.length < 16) || (textField_cardNo.text.length >19) ) {
        
        [UsefulUtil showAlertView:@"请输入正确的银行卡号!"];
        return;
    }else  { //开始访问server得到签名数据 ,这儿记得加一个参数bankId
        
        NSDictionary *dic_params = @{@"userId":[UserManager sharedUserManager].user.user_userId,@"amountFee":textField_amount.text,@"cardNo":textField_cardNo.text,@"appRequest":@"2",@"payChannel":@"1",@"payPlatform":@"2"};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [[NetworkUtil sharedNetworkUtil] zzjrUserIDCardBindigByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSDictionary* dic_sign = parsedData ;
            
            if([dic_sign[@"status"] integerValue] == 0) {
                
                if ([dic_sign[@"result"] count] > 0 ) {
                    
                    NSLog(@"服务器返回的签名内容!:%@",dic_sign[@"result"]);
                    
                    self.str_order_no = dic_sign[@"result"][@"no_order"];
                    
                    [self.sdk presentVerifyPaySdkInViewController:self withTraderInfo:dic_sign[@"result"]];
                }
                
            }else  {
                
                [UsefulUtil showAlertView:dic_sign[@"msg"]];
                
            }
        }];
    }
}

// 连连支付SDK的回调

- (void)paymentEnd:(LLPayResult)resultCode withResultDic:(NSDictionary*)dic {
  
    NSLog(@"连连支付SDK的回调:%@＝＝支付结果:%d",dic[@"ret_msg"],resultCode);

    // 如果支付成功，跳转到支付成功页面，看看支付成功，连连返回的数据决定
    
    if (resultCode == 0) {
        
        DepositSuccessViewController *successVC= [[DepositSuccessViewController alloc] init];
       
        UITextField *textField_amount = (UITextField *)[self.view_header viewWithTag:51];
        
        [successVC setStr_amount:textField_amount.text];
        [self.navigationController pushViewController:successVC animated:YES];
    }
}

- (void)rateCalculation:(BCTextField *) textFiled {

    NSString *str_money = textFiled.text;
    
    // 用户输入的值算出来的收入
    NSString *str_rate_ourSelf_beforeSub = [NSString stringWithFormat:@"%f",str_money.floatValue * self.user_currentRate /36500];

    // 截取二位后的收入
    NSString *str_rate_ourSelf = [NSString stringWithFormat:@"%.2f",str_rate_ourSelf_beforeSub.floatValue];

    //用户当前的加息值
    NSString *str_userRate = [NSString stringWithFormat:@"%.f",self.user_currentRate];
    
    //是银行的多少倍
    NSString *str_rate_bank = [NSString stringWithFormat:@"%.f", self.user_currentRate/0.25];
    
    
    NSString *label_content = [NSString stringWithFormat:@"当前利率%@%%,每日预期收益%@元,是银行活期的%@倍",str_userRate,str_rate_ourSelf,str_rate_bank ];
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:label_content];
    
    [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(4, str_userRate.length)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(12+ str_userRate.length, str_rate_ourSelf.length)];
    
    [attrStr addAttribute:NSForegroundColorAttributeName value:REDCOLOR range:NSMakeRange(label_content.length-1 -str_rate_bank.length, str_rate_bank.length)];
    
    [self.label_promtRate setAttributedText:attrStr];
    
}

- (void) setKeyBoardAndCorrespondingLimitationForTextFiledInViewHeader {
    
    for (UIView *tmp in self.view_header.subviews) {
        
        if ([tmp isMemberOfClass:[UITextField class]]) {
            
            UITextField *textFiled_tmp = (UITextField *) tmp;
            
            [textFiled_tmp setKeyboardType:UIKeyboardTypeDecimalPad];
        }
    }
}

- (void) bankSelection: (UITapGestureRecognizer *) tap { //跳到选择银行列表
    
    BankSelectionViewController *bankVC = [[BankSelectionViewController alloc] initWithBlock:^(NSString *bankName, NSString *bankId) {
        
        [self.label_bank setTextColor:[UIColor blackColor]];
        [self.label_bank setText:bankName];
    
        BCTextField *textField = [self.view_header viewWithTag:51];
        [textField setText:@""];
    }];
   
    [self.navigationController pushViewController:bankVC animated:YES];
}

// keep this method as empty
- (void) swiperGestureHandle:(UISwipeGestureRecognizer *) swipe {
    
}

- (void) backToPreviousPage {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
